//
//  XDLoginViewController.m
//  iphone.mobileoa
//
//  Created by 李亚春 on 13-5-20.
//  Copyright (c) 2013年 Epoint. All rights reserved.
//

#import "XDLoginViewController.h"
#import "XDMainViewController.h"
#import "LoginCheckTask.h"
#import "DBFrameService.h"
#import "DbUtil.h"
#import "XDSettingViewController.h"
#import "UIViewController+MJPopupViewController.h"
#import "XDPopViewController.h"
#import "PopoverView.h"
#import "CheckUpdateTask.h"
#import "CommonUtil.h"


@interface XDLoginViewController ()
{
    NSString *checkUpdateTaskGuid;
}
@end

@implementation XDLoginViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
- (IBAction)loginAction:(id)sender {
    
    [self startLogin];
    
    
}

-(void)startLogin
{
    if (self.tfPassword.text.length==0||self.tfLoginId.text.length==0) {
        [UITool toast:@"用户名和密码不能为空！"];
        return;
    }
    [self showMBPHUD];
    
    NSMutableDictionary *params = self.getPassDictionary;
    [params setObject:self.tfLoginId.text forKey:EP_ConfigKey_loginid];
    [params setObject:self.tfPassword.text forKey:EP_ConfigKey_password];
    
    logintaskguid = [[[LoginCheckTask alloc]initWithContext:self andParams:params]startTask];
}


-(void)refreshUIWithThreadGuid:(NSString *)threadGuid andData:(NSObject *)obj
{
    [self hideMBPHUD];
    if ([threadGuid isEqualToString:logintaskguid]) {
        NSString *bs = (NSString *)obj;
        if ([self validateXML:bs]) {
            NSString *UserLogin = [StringUtil getXMLFormatedAttribute:bs :@"UserLogin"];
            if ([UserLogin.lowercaseString isEqualToString:@"true"]) {
                
                
                NSString *UserGuid = [StringUtil getXMLFormatedAttribute:bs :@"UserGuid"];
                NSString *UserDisplayName = [StringUtil getXMLFormatedAttribute:bs :@"UserDisplayName"];
                NSString *BaseOuGuid = [StringUtil getXMLFormatedAttribute:bs :@"BaseOuGuid"];
                NSString *NewMailsCount = [StringUtil getXMLFormatedAttribute:bs :@"NewMailsCount"];
                NSString *NewWaitHandleCount = [StringUtil getXMLFormatedAttribute:bs :@"NewWaitHandleCount"];
                
                NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
                [dic setObject:NewMailsCount forKey:@"NewMailsCount"];
                [dic setObject:NewWaitHandleCount forKey:@"NewWaitHandleCount"];
                XDMainViewController *mainview = [[XDMainViewController alloc]initWithParams:dic];
                [self.navigationController pushViewController:mainview animated:YES];
                
                [DBFrameService setConfigValue:EP_ConfigKey_userguid value:UserGuid];
                [DBFrameService setConfigValue:EP_ConfigKey_password value:self.tfPassword.text];
                [DBFrameService setConfigValue:EP_ConfigKey_loginid value:self.tfLoginId.text];
                [DBFrameService setConfigValue:EP_ConfigKey_displayname value:UserDisplayName];
                [DBFrameService setConfigValue:EP_ConfigKey_baseouguid value:BaseOuGuid];
                [DBFrameService setConfigValue:EP_ConfigKey_isLogin value:@"1"];
            }
            else
            {
                [UITool toast:@"用户名或密码错误！"];
            }
        }
    }
    else if ([threadGuid isEqualToString:checkUpdateTaskGuid]) {
        NSString *bs = (NSString *)obj;
        NSString *result = [StringUtil getXMLFormatedAttribute:bs :@"result"];
        
        
        
        if ([result isEqualToString:@"YES"]) {
            NSString *info = [StringUtil getXMLFormatedAttribute:bs :@"info"];
            NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
            [params setObject:info forKey:@"updateinfo"];
            XDUpdatePanelViewController *vc = [[XDUpdatePanelViewController alloc]initWithParams:params];
            vc.delegate = self;
            [self presentPopupViewController:vc animationType:MJPopupViewAnimationSlideBottomBottom];
        }
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"登录";
    self.tfLoginId.delegate = self;
    self.tfPassword.delegate = self;
    self.lbVersion.text = [NSString stringWithFormat:@"版本号：V%@",[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]];
    self.lbCopyrightInfo.text = NSLocalizedString(@"CopyrightInformation", @"");
    [DBFrameService setConfigValue:EP_ConfigKey_isLogin value:@"0"];
    self.tfLoginId.text = [DBFrameService getConfigValue:@"loginid"];
    self.tfPassword.text = [DBFrameService getConfigValue:@"password"];
    
    [UITool setGlossyButtonWithRed:68.0f green:151.0f blue:200.0f :[self.view viewWithTag:1003]];
    
    self.navigationItem.leftBarButtonItem = nil;
    self.navigationItem.hidesBackButton = YES;
    //self.loginPanel.layer.cornerRadius = 10;
    self.loginPanel.layer.borderWidth = 0.5;
    [self.loginPanel.layer setBorderColor:[[UIColor lightGrayColor] CGColor]];
    UIButton* rightButton= [[UIButton alloc] initWithFrame:CGRectMake(0,0,40,20)];
    [rightButton setBackgroundImage:[UIImage imageNamed:@"top_set"] forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(gotoconfig) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItem = leftBarButtonItem;
    [leftBarButtonItem release];
    [rightButton release];
    
    checkUpdateTaskGuid = [[[CheckUpdateTask alloc]initWithContext:self andParams:self.getPassDictionary]startTask];
    
    if([[DBFrameService getConfigValue:EP_ConfigKey_isAutoLogin]isEqualToString:@"1"]){
    if (self.tfPassword.text.length>0&&self.tfLoginId.text.length>0) {
        [self startLogin];
    }
    }
}

-(void)viewDidAppear:(BOOL)animated
{
    
        if (self.tfPassword.text.length==0||self.tfLoginId.text.length==0) {
            checkUpdateTaskGuid = [[[CheckUpdateTask alloc]initWithContext:self andParams:self.getPassDictionary]startTask];
        }
}

-(void)gotoconfig
{
    XDSettingViewController *vc = [[XDSettingViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [_tfLoginId release];
    [_tfPassword release];
    [_lbVersion release];
    [_lbCopyrightInfo release];
    [_loginPanel release];
    [super dealloc];
}
- (void)viewDidUnload {
    [self setTfLoginId:nil];
    [self setTfPassword:nil];
    [self setLbVersion:nil];
    [self setLbCopyrightInfo:nil];
    [self setLoginPanel:nil];
    [super viewDidUnload];
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    [textField resignFirstResponder];
}


- (IBAction)backgroundTap:(UITextField *)sender {
    [sender resignFirstResponder];
    if (sender.tag==1002) {
        [self loginAction:sender];
    }else if(sender.tag==1001)
    {
        [self.tfPassword becomeFirstResponder];
    }
}

-(void)okAction
{
    [self dismissPopupViewControllerWithanimationType:MJPopupViewAnimationSlideBottomTop];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"itms-services://?action=download-manifest&url=%@",[CommonUtil getDownloadUrl:@"updateclient/dis.plist"]]]];
}

-(void)cancelPopWindow
{
    [self dismissPopupViewControllerWithanimationType:MJPopupViewAnimationSlideBottomBottom];
}

@end
